# -*- coding: utf-8 -*-

import pytest
import base64
import zipfile, os

from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.webdriver.appium_service import AppiumService

# 开启服务端
APPIUM_HOST = '127.0.0.1'
APPIUM_PORT = 4723
@pytest.fixture(scope="session")
def start_appium_service():
    server = AppiumService()
    server.start(args=['--address', APPIUM_HOST, '-p', str(APPIUM_PORT)], timeout_ms=60000)
    yield server
    server.stop()

# 创建客户端到服务端的会话
def create_appium_session_by_api(custom_opts = None, appium_host = APPIUM_HOST, appium_port = APPIUM_PORT):
    options = UiAutomator2Options()
    if custom_opts is not None:
        options.load_capabilities(custom_opts)
    return webdriver.Remote(f'http://{appium_host}:{appium_port}', options=options)

# !发送文件到被测设备
def test_push_file(start_appium_service):
    custom_opts = {
        "appium:avd": "testPhone",
    }

    driver = create_appium_session_by_api(custom_opts)
    # 直接指定待传输文件的本地路径
    driver.push_file(destination_path="/sdcard/file_test", source_path="/tmp/file_test")

    # 通过base64编码后进行传输
    binary_data = 'hello android'.encode('utf-8')
    driver.push_file(destination_path="/sdcard/file_test_base64", base64data=f"{base64.b64encode(binary_data).decode('utf-8')}")
    driver.quit()


# !获取被测设备上的文件
def test_pull_file(start_appium_service):
    custom_opts = {
        "appium:avd": "testPhone",
    }

    driver = create_appium_session_by_api(custom_opts)
    data = 'hello android'
    driver.push_file(destination_path="/sdcard/file_test_base64", base64data=f"{base64.b64encode(data.encode('utf-8')).decode('utf-8')}")

    # 读取被测设备上文件
    base64_content = driver.pull_file("/sdcard/file_test_base64")
    assert (base64.b64decode(base64_content)).decode('utf-8') == data
    driver.quit()


# !获取被测设备上的文件夹
def test_pull_folder(start_appium_service):
    custom_opts = {
        "appium:avd": "testPhone",
    }

    driver = create_appium_session_by_api(custom_opts)
    data = 'hello android'
    driver.push_file(destination_path="/sdcard/Download/file_test_base64", base64data=f"{base64.b64encode(data.encode('utf-8')).decode('utf-8')}")

    # 读取被测设备上文件夹
    base64_zip_folder_content = driver.pull_folder("/sdcard/Download/")

    # 解析base64的内容，并存储成文件
    zip_folder_content = (base64.b64decode(base64_zip_folder_content))
    with open("/tmp/test.zip", "wb") as f:
        f.write(zip_folder_content)

    # 解压文件夹
    with zipfile.ZipFile("/tmp/test.zip", 'r') as zip_f:
        zip_f.extractall("/tmp")
    
    assert os.path.exists("/tmp/Download/file_test_base64")

    file_content = ""
    with open("/tmp/Download/file_test_base64") as f:
        file_content = f.read()
    assert file_content == data

    driver.quit()